// pages/reservation/personal_form.js
const app = getApp()
import api from '../../utils/api'

Page({
  data: {
    date: '',
    time_slot_id: '',
    slot: null,
    time: '',

    visitors: [
      { id: Date.now(), name: '', id_type: 'idcard', id_type_label: '身份证', id_number: '', contact_phone: '' }
    ],
    idTypeOptions: [
      { value: 'idcard', label: '身份证' },
      { value: 'passport', label: '护照' },
      { value: 'tw_permit', label: '台胞证' }
    ],

    canSubmit: false,
    submitting: false,
    showContactPicker: false,
    contactsLoading: false,
    contacts: [],
    filteredContacts: [],
    contactSearch: '',
    contactPickTargetIndex: 0
  },

  onLoad(query) {
    const { date, time_slot_id } = query || {}
    this.setData({ date, time_slot_id })
    try {
      const slot = wx.getStorageSync('selected_slot') || null
      if (slot) {
        const time = slot.start_time + ' - ' + slot.end_time
        this.setData({ slot, time})
      }
    } catch (e) {}
    this.prefillContactPhone()
    this.updateCanSubmit()
  },

  // 预填充联系人手机号（若用户资料里有）
  prefillContactPhone() {
    const phone = app?.globalData?.userInfo?.phone || ''
    if (phone && this.data.visitors && this.data.visitors.length) {
      const list = this.data.visitors.slice()
      list[0].contact_phone = list[0].contact_phone || phone
      this.setData({ visitors: list })
    }
  },

  onInput(e) {
    const { index, field } = e.currentTarget.dataset
    const value = e.detail.value
    const list = this.data.visitors.slice()
    list[index][field] = value
    this.setData({ visitors: list })
    this.updateCanSubmit()
  },

  onIdTypeChange(e) {
    const index = Number(e.currentTarget.dataset.index)
    const option = this.data.idTypeOptions[e.detail.value]
    const list = this.data.visitors.slice()
    list[index].id_type = option.value
    list[index].id_type_label = option.label
    this.setData({ visitors: list })
    this.updateCanSubmit()
  },

  addVisitor() {
    if (this.data.visitors.length >= 5) {
      wx.showToast({ title: '最多添加5位观众', icon: 'none' })
      return
    }
    const v = { id: Date.now() + Math.random(), name: '', id_type: 'idcard', id_type_label: '身份证', id_number: '' }
    this.setData({ visitors: [...this.data.visitors, v] })
    this.updateCanSubmit()
  },

  removeVisitor(e) {
    const idx = Number(e.currentTarget.dataset.index)
    if (idx === 0) return // 第一位不可删除
    const list = this.data.visitors.slice()
    list.splice(idx, 1)
    this.setData({ visitors: list })
    this.updateCanSubmit()
  },

  isValidPhone(phone) {
    const reg = /^(1\d{10})$/
    return reg.test(String(phone || '').trim())
  },

  updateCanSubmit() {
    const hasValidFirst = (() => {
      const v = this.data.visitors[0]
      if (!v) return false
      return !!(v.name && v.id_number && this.isValidPhone(v.contact_phone))
    })()

    const othersOk = this.data.visitors.slice(1).every(v => v.name && v.id_number)
    const countOk = this.data.visitors.length > 0 && this.data.visitors.length <= 5
    this.setData({ canSubmit: hasValidFirst && othersOk && countOk })
  },

  async submit() {
    if (!this.data.canSubmit || this.data.submitting) return

    const isLoggedIn = await app.checkAuth()
    if (!isLoggedIn) return

    this.setData({ submitting: true })

    try {
      const first = this.data.visitors[0]
      const payload = {
        time_slot_id: Number(this.data.time_slot_id),
        visit_date: this.data.date,
        visitor_count: this.data.visitors.length,
        contact_name: first.name,
        contact_phone: first.contact_phone,
        special_requirements: '',
        // 携带详细观众信息，便于后端按需存储/校验
        visitors: this.data.visitors.map(v => ({
          name: v.name,
          id_type: v.id_type || 'idcard',
          id_number: v.id_number
        }))
      }
    
      const res = await api.reservation.create(payload)
    
      // 提交成功后跳转到个人预约记录页
      wx.redirectTo({
        url: '/pages/profile/reservations'
      })
    } catch (err) {
      wx.showToast({ title: err.message || '提交失败', icon: 'none' })
    } finally {
      this.setData({ submitting: false })
    }
  }, // 确保这里有逗号
  // ===== 常用联系人：打开弹窗并加载列表（根据卡片索引） =====
  async openContactPicker(e) {
    const idx = Number(e?.currentTarget?.dataset?.index ?? 0)
    this.setData({ showContactPicker: true, contactPickTargetIndex: idx })
    if (this.data.contacts.length === 0) {
      await this.fetchContacts()
    }
  },

  closeContactPicker() {
    this.setData({ showContactPicker: false })
  },

  async fetchContacts() {
    try {
      this.setData({ contactsLoading: true })
      // 拉取前 100 条常用联系人（足够覆盖大多数用户）
      const res = await api.visitors.getList({ page: 1, pageSize: 100, keyword: '' })
      const list = Array.isArray(res?.list) ? res.list : []
      this.setData({
        contacts: list,
        filteredContacts: list,
        contactsLoading: false
      })
    } catch (e) {
      this.setData({ contactsLoading: false })
      wx.showToast({ title: '加载常用联系人失败', icon: 'none' })
    }
  },

  onContactSearchInput(e) {
    const keyword = String(e.detail.value || '').trim()
    const filtered = this.data.contacts.filter(c => {
      const name = String(c.name || '')
      const phone = String(c.phone || c.contact_phone || '')
      const idnum = String(c.id_number || '')
      return (
        name.includes(keyword) ||
        phone.includes(keyword) ||
        idnum.includes(keyword)
      )
    })
    this.setData({
      contactSearch: keyword,
      filteredContacts: filtered
    })
  },

  getIdTypeLabel(type) {
    const opt = this.data.idTypeOptions.find(o => o.value === type)
    return opt ? opt.label : '身份证'
  },

  onPickContact(e) {
    const idx = Number(e.currentTarget.dataset.index) // 选择弹窗中被选中的联系人索引
    const item = this.data.filteredContacts[idx]
    if (!item) return

    const target = Number(this.data.contactPickTargetIndex || 0) // 目标卡片索引
    const list = this.data.visitors.slice()
    const idType = item.id_type || 'idcard'

    list[target] = {
      ...list[target],
      name: item.name || '',
      id_type: idType,
      id_type_label: item.id_type_label || this.getIdTypeLabel(idType),
      id_number: item.id_number || ''
    }
    // 仅当目标是第一个卡片时，更新联系电话
    if (target === 0) {
      list[0].contact_phone = item.phone || item.contact_phone || list[0].contact_phone || ''
    }

    this.setData({ visitors: list, showContactPicker: false })
    this.updateCanSubmit()
  }
})